package com.hifar.test.collectdata.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.abi.utils.sys.SysUtils;
import com.hifar.fw.utils.id.IdUtils;
import com.hifar.fw.utils.lang.DateUtils;
import com.hifar.fw.utils.lang.NumberUtils;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.maindatasource.service.ICollectdbDataSourceService;
import com.hifar.test.collectdata.constant.CollectConsts;
import com.hifar.test.collectdata.pojo.CollectData;
import com.hifar.test.collectdata.pojo.IntervalBean;
import com.hifar.test.collectdata.pojo.TemperatureVo;
import com.hifar.test.collectdata.pojo.VO.*;
import com.hifar.test.collectdata.pojo.VibarateVo;
import com.hifar.test.collectdata.service.ICollectDataService;
import com.hifar.test.equip.pojo.HfResEquip;
import com.hifar.test.equip.service.IHfResEquipService;
import com.hifar.sys.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 采集数据表 前端控制器 default
 * </p>
 *
 * @author wangkepeng
 * @since 2024-12-17 11:08:21
 */
@RestController
@RequestMapping("/api/busi/test/collectDataController")
@Api(tags = "采集数据表功能")
public class CollectDataController {

    @Autowired
    private ICollectDataService collectDataService;

    @Autowired
    private IBaseOssFilesService baseOssFilesService;
    @Autowired
    private ICollectdbDataSourceService collectdbDataSourceService;

    @Autowired
    private IHfResEquipService hfResEquipService;

    @ApiOperation("分页列表查询")
    @PostMapping("/listPageClimate")
    public BusiResponse listPageClimate(@RequestBody @Validated CollectDataQueryParamVO collectDataQueryParamVO) {
        Integer pageNo = collectDataQueryParamVO.getPageNo();
        Integer pageSize = collectDataQueryParamVO.getPageSize();
        Page<ClimateCollectDataVO> page = new Page<>(pageNo, pageSize);
        Date startTime = collectDataQueryParamVO.getStartTime();
        Date endTime = collectDataQueryParamVO.getEndTime();
        String equipId = collectDataQueryParamVO.getEquipId();
        Page<ClimateCollectDataVO> pageData = collectDataService.listPageClimate(page, equipId, startTime, endTime);
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }

    @ApiOperation("分页列表查询")
    @PostMapping("/listClimate")
    public BusiResponse listClimate(@RequestBody @Validated CollectDataQueryParamVO collectDataQueryParamVO) {
        Date startTime = collectDataQueryParamVO.getStartTime();
        Date endTime = collectDataQueryParamVO.getEndTime();
        String equipId = collectDataQueryParamVO.getEquipId();
        List<ClimateCollectDataVO> listClimate = collectDataService.listClimate(equipId, startTime, endTime);
        return BusiResponse.OK(listClimate);
    }

    @ApiOperation("分页列表查询")
    @PostMapping("/listPageDynamics")
    public BusiResponse listPageDynamics(@RequestBody @Validated CollectDataQueryParamVO collectDataQueryParamVO) {
        Integer pageNo = collectDataQueryParamVO.getPageNo();
        Integer pageSize = collectDataQueryParamVO.getPageSize();
        Page<DynamicsCollectDataVO> page = new Page<>(pageNo, pageSize);
        Date startTime = collectDataQueryParamVO.getStartTime();
        Date endTime = collectDataQueryParamVO.getEndTime();
        String equipId = collectDataQueryParamVO.getEquipId();
        Page<DynamicsCollectDataVO> pageData = collectDataService.listPageDynamics(page, equipId, startTime, endTime);
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }

    @ApiOperation("列表查询")
    @PostMapping("/listDynamics")
    public BusiResponse listDynamics(@RequestBody @Validated CollectDataQueryParamVO collectDataQueryParamVO) {
        Date startTime = collectDataQueryParamVO.getStartTime();
        Date endTime = collectDataQueryParamVO.getEndTime();
        String equipId = collectDataQueryParamVO.getEquipId();
        List<DynamicsCollectDataVO> listDynamics = collectDataService.listDynamics(equipId, startTime, endTime);
        return BusiResponse.OK(listDynamics);
    }


    @PostMapping(value = "/listcollectdata")
    @ApiOperation(value = "采集数据表功能:分页查询列表")
    public BusiResponse listcollectdata(HttpServletRequest request) {

        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        Long pageNo = NumberUtils.parseLong(pageInfo.get("pageNo"), 1);
        Integer pageSize = (Integer) pageInfo.get("pageSize");
        Integer year = NumberUtils.parseInt(StringUtils.trimNull(pageInfo.get("year")), 2024);

        String startTimeStr = StringUtils.trimNull(pageInfo.get("startTime"));
        String endTimeStr = StringUtils.trimNull(pageInfo.get("endTime"));

        Date startDateTime = null;
        Date endDateTime = null;
        try {
            startDateTime = DateUtils.paseTime(startTimeStr, DateUtils.YYYY_MM_DD_HH_MM_SS);
        } catch (Exception e) {

            e.printStackTrace();
        }
        try {
            endDateTime = DateUtils.paseTime(endTimeStr, DateUtils.YYYY_MM_DD_HH_MM_SS);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Date currentTime = new Date();

        int currentYear = getYear(currentTime);

        String equipId = StringUtils.trimNull(pageInfo.get("equipId"));
        String runningRecordType = "";
        // 查询设备信息
        HfResEquip equip = hfResEquipService.getById(equipId);
        String equipCode = "";
        if (equip == null) {
            return BusiResponse.error(400, "设备未查询到！");
        } else {
            runningRecordType = equip.getEquipTypeCode();
            equipCode = equip.getEquipCode();
        }

        if ("".equals(equip.getEquipCode())) {
            return BusiResponse.error(400, "设备编号未查询到！");
        }

        // 根据时间间隔计算总条数start

        String collectDataInterval = SysUtils.getSwithValueNoTenantId(new com.hifar.fw.utils.bean.BusiRequest(),
                "collectDataInterval");
        double intervalParam = NumberUtils.parseDouble(collectDataInterval, 1);
        Date startTime = null;


        if (startDateTime != null) {
            startTime = startDateTime;
        } else {
            startTime = DateUtils.paseTime(currentYear + "-01-01 00:00:00", DateUtils.YYYY_MM_DD_HH_MM_SS);

        }
        Date endTime = null;
        if (endDateTime != null) {
            endTime = endDateTime;
        } else {
            endTime = DateUtils.paseTime(currentYear + "-12-31 59:59:59", DateUtils.YYYY_MM_DD_HH_MM_SS);

        }

        IntervalBean interval = new IntervalBean();
        interval.setStartTime(startTime);
        interval.setEndTime(endTime);
        interval.setInteralValue(intervalParam);
        interval.setPageNo(pageNo);
        interval.setPageSize(pageSize);


        Page<Map<String, Object>> dataPage2 = new Page<>(pageNo, pageSize);
        String sqlData = "select  `timestamp` FROM " + CollectConsts.TABLE_PREFIX + equipCode + "_" + year + " where tagtype=1 and tagname like '%PV'    and  `timestamp`>='" + DateUtils.formatTime(startTime, DateUtils.YYYY_MM_DD_HH_MM_SS) + "' and `timestamp`<='"
                + DateUtils.formatTime(endTime, DateUtils.YYYY_MM_DD_HH_MM_SS) + "' "
                + "  group by `timestamp`   order by `timestamp` asc ";
        dataPage2 = collectdbDataSourceService.selectPage(dataPage2, sqlData);
        Date tempDate = null;
        LocalDateTime dataTime;
        Date dateTemp;

        if (dataPage2 != null) {
            List<Map<String, Object>> dataList = dataPage2.getRecords();
            List<Date> dateList = new ArrayList<Date>();

            for (Map<String, Object> map : dataList) {
                dataTime = (LocalDateTime) map.get("timestamp");

                ZoneId zoneId = ZoneId.systemDefault();
                ZonedDateTime zdt = dataTime.atZone(zoneId);
                dateTemp = Date.from(zdt.toInstant());
                tempDate = dateTemp;
                dateList.add(tempDate);
            }
            interval.setDataList(dateList);
            interval.setTotal(dataPage2.getTotal());
            interval.setPageTotal(dataPage2.getPages());
        }


        // 根据时间间隔计算总条数end
        List<Date> dateList = interval.getDataList();
        Date firstDate = null;
        if (dateList != null && dateList.size() > 0) {
            firstDate = dateList.get(0);
        } else {
            firstDate = startTime;
        }

        firstDate = new Date(firstDate.getTime() - 40000);

        Date lastDate = null;
        if (dateList != null && dateList.size() > 1) {
            lastDate = dateList.get(dateList.size() - 1);
        } else {
            lastDate = endTime;
        }

        lastDate = new Date(lastDate.getTime() + 40000);

        // 查询某个时间段的数据
        List<Map<String, Object>> originalDataList = new ArrayList<Map<String, Object>>();
        try {
            Page<Map<String, Object>> dataPage = new Page<Map<String, Object>>(1, 20);
            String sql = "select * from " + CollectConsts.TABLE_PREFIX + equipCode + "_" + year + " where timestamp>='"
                    + DateUtils.formatTime(firstDate, DateUtils.YYYY_MM_DD_HH_MM_SS) + "' and timestamp<='"
                    + DateUtils.formatTime(lastDate, DateUtils.YYYY_MM_DD_HH_MM_SS)
                    + "' and tagtype=1  and tagname like '%PV'  order by timestamp asc  ";
            dataPage = collectdbDataSourceService.selectPage(dataPage, sql);
            originalDataList.addAll(dataPage.getRecords());

            Long totalPageOriginal = dataPage.getPages();
            // 第二页开始到结束页的数据
            for (Long i = 2L; i <= totalPageOriginal; i++) {
                dataPage = new Page<Map<String, Object>>(i, 20);
                dataPage = collectdbDataSourceService.selectPage(dataPage, sql);
                originalDataList.addAll(dataPage.getRecords());
            }
        } catch (Exception e) {
            return BusiResponse.error(400,
                    "设备[" + equip.getEquipName() + "]在采集数据库缺少表[" + equipCode + "_" + year + "]请检查采集数据库表的配置！");
        }

        List<TemperatureVo> retVoTemperatureList = null;

        List<VibarateVo> retVoVibarateList = null;
        // 温控类
        if ("1".equals(runningRecordType)) {
            Map<String, List<Map<String, Object>>> typeDataList = originalDataList.stream()
                    .collect(Collectors.groupingBy(item -> StringUtils.trimNull(item.get("tagname"))));
            TemperatureVo vo = null;
            retVoTemperatureList = new ArrayList<TemperatureVo>();
            for (Date date : dateList) {
                vo = new TemperatureVo();
                vo.setRunningTime(date);
                vo.setTimeLong(date.getTime());
                retVoTemperatureList.add(vo);
            }
            Map<Long, TemperatureVo> keyTempratrue = retVoTemperatureList.stream()
                    .collect(Collectors.toMap(item -> item.getTimeLong(), item -> item, (o1, o2) -> o1));

            // 查询温度start
            List<Map<String, Object>> temperatureList = typeDataList.get(CollectConsts.TEMPERATURE_PV);
            Long timeTarget = 0L;
            Long timeCurrent = 0L;
            Long timeDiff = 0L;
            Long timeDiffEnd = 0L;
            Object curtimeObj;
            Map<String, Object> curObj = null;
            Map<String, Object> endObj = null;

            for (Date date : dateList) {
                timeTarget = date.getTime();
                TemperatureVo vo1 = keyTempratrue.get(timeTarget);
                vo1.setRunningTime(date);
                timeDiffEnd = null;
                endObj = null;
                if (temperatureList != null) {
                    for (Map<String, Object> currMap : temperatureList) {


                        curtimeObj = currMap.get("timestamp");
                        if (curtimeObj != null) {

                            dataTime = (LocalDateTime) curtimeObj;

                            ZoneId zoneId = ZoneId.systemDefault();
                            ZonedDateTime zdt = dataTime.atZone(zoneId);
                            dateTemp = Date.from(zdt.toInstant());

                            timeCurrent = dateTemp.getTime();
                            timeDiff = Math.abs(timeCurrent - timeTarget);
                            if (timeDiff == 0) {
                                timeDiffEnd = 0L;
                                endObj = currMap;
                                break;
                            } else {
                                if (timeDiffEnd == null) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                } else if (timeDiff < timeDiffEnd) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                }
                            }
                        }
                    }
                }
                if (endObj != null && timeDiffEnd < intervalParam * 60000 * 0.9) {

                    if (vo1 != null) {
                        vo1.setTemperature(StringUtils.trimNull(endObj.get("tagvalue")));
                        vo1.setTemperatureId(StringUtils.trimNull(endObj.get("tagid")));
                        vo1.setRemarks(StringUtils.trimNull(endObj.get("remarks")));
                        vo1.setUsername(StringUtils.trimNull(endObj.get("username")));
                    }
                }
            }

            // 查询温度end
            // 查询湿度start
            List<Map<String, Object>> humidityList = typeDataList.get(CollectConsts.HUMIDITY_PV);
            for (Date date : dateList) {
                timeTarget = date.getTime();
                timeDiffEnd = null;
                endObj = null;
                if (humidityList != null) {
                    for (Map<String, Object> currMap : humidityList) {
                        curtimeObj = currMap.get("timestamp");
                        if (curtimeObj != null) {


                            dataTime = (LocalDateTime) curtimeObj;
                            ZoneId zoneId = ZoneId.systemDefault();
                            ZonedDateTime zdt = dataTime.atZone(zoneId);
                            dateTemp = Date.from(zdt.toInstant());

                            timeCurrent = dateTemp.getTime();
                            timeDiff = Math.abs(timeCurrent - timeTarget);
                            if (timeDiff == 0) {
                                timeDiffEnd = 0L;
                                endObj = currMap;
                                break;
                            } else {
                                if (timeDiffEnd == null) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                } else if (timeDiff < timeDiffEnd) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                }
                            }
                        }
                    }
                }
                if (endObj != null && timeDiffEnd < intervalParam * 60000 * 0.9) {
                    TemperatureVo vo1 = keyTempratrue.get(timeTarget);
                    if (vo1 != null) {
                        vo1.setHumidity(StringUtils.trimNull(endObj.get("tagvalue")));
                        vo1.setHumidityId(StringUtils.trimNull(endObj.get("tagid")));
                    }
                }
            }
            // 查询湿度end
            // 查询气压start
            List<Map<String, Object>> pressureList = typeDataList.get(CollectConsts.PRESSURE_PV);
            for (Date date : dateList) {
                timeTarget = date.getTime();
                timeDiffEnd = null;
                endObj = null;
                if (pressureList != null) {
                    for (Map<String, Object> currMap : pressureList) {
                        curtimeObj = currMap.get("timestamp");
                        if (curtimeObj != null) {
                            dataTime = (LocalDateTime) curtimeObj;
                            ZoneId zoneId = ZoneId.systemDefault();
                            ZonedDateTime zdt = dataTime.atZone(zoneId);
                            dateTemp = Date.from(zdt.toInstant());

                            timeCurrent = dateTemp.getTime();
                            timeDiff = Math.abs(timeCurrent - timeTarget);
                            if (timeDiff == 0) {
                                timeDiffEnd = 0L;
                                endObj = currMap;
                                break;
                            } else {
                                if (timeDiffEnd == null) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                } else if (timeDiff < timeDiffEnd) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                }
                            }
                        }
                    }
                }
                if (endObj != null && timeDiffEnd < intervalParam * 60000 * 0.9) {
                    TemperatureVo vo1 = keyTempratrue.get(timeTarget);
                    if (vo1 != null) {
                        vo1.setAirPressure(StringUtils.trimNull(endObj.get("tagvalue")));
                        vo1.setAirPressureId(StringUtils.trimNull(endObj.get("tagid")));
                    }
                }
            }
            // 查询气压end
            // 查询试验性质start
            List<Map<String, Object>> propertyList = typeDataList.get(CollectConsts.TESTPROPERY_PV);
            for (Date date : dateList) {
                timeTarget = date.getTime();
                timeDiffEnd = null;
                endObj = null;
                if (propertyList != null) {
                    for (Map<String, Object> currMap : propertyList) {
                        curtimeObj = currMap.get("timestamp");
                        if (curtimeObj != null) {

                            dataTime = (LocalDateTime) curtimeObj;
                            ZoneId zoneId = ZoneId.systemDefault();
                            ZonedDateTime zdt = dataTime.atZone(zoneId);
                            dateTemp = Date.from(zdt.toInstant());

                            timeCurrent = dateTemp.getTime();


                            timeDiff = Math.abs(timeCurrent - timeTarget);
                            if (timeDiff == 0) {
                                timeDiffEnd = 0L;
                                endObj = currMap;
                                break;
                            } else {
                                if (timeDiffEnd == null) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                } else if (timeDiff < timeDiffEnd) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                }
                            }
                        }
                    }
                }
                if (endObj != null && timeDiffEnd < intervalParam * 60000 * 0.9) {
                    TemperatureVo vo1 = keyTempratrue.get(timeTarget);
                    if (vo1 != null) {
                        vo1.setTestProperty(StringUtils.trimNull(endObj.get("tagvalue")));
                        vo1.setTestPropertyId(StringUtils.trimNull(endObj.get("tagid")));
                    }
                }
            }

            // 查询试验性质end
        } else if ("2".equals(runningRecordType)) {
            Map<String, List<Map<String, Object>>> typeDataList = originalDataList.stream()
                    .collect(Collectors.groupingBy(item -> StringUtils.trimNull(item.get("tagname"))));
            VibarateVo vo = null;
            retVoVibarateList = new ArrayList<VibarateVo>();
            for (Date date : dateList) {
                vo = new VibarateVo();
                vo.setRunningTime(lastDate);
                vo.setTimeLong(date.getTime());
                retVoVibarateList.add(vo);
            }
            Map<Long, VibarateVo> keyVibarateVo = retVoVibarateList.stream()
                    .collect(Collectors.toMap(item -> item.getTimeLong(), item -> item, (o1, o2) -> o1));

            // 查询方向start
            List<Map<String, Object>> directList = typeDataList.get(CollectConsts.VIARANTDIRECT_PV);
            Long timeTarget = 0L;
            Long timeCurrent = 0L;
            Long timeDiff = 0L;
            Long timeDiffEnd = 0L;
            Object curtimeObj;
            Map<String, Object> curObj = null;
            Map<String, Object> endObj = null;

            for (Date date : dateList) {
                timeTarget = date.getTime();
                VibarateVo vo1 = keyVibarateVo.get(timeTarget);
                vo1.setRunningTime(date);
                timeDiffEnd = null;
                endObj = null;
                if (directList != null) {
                    for (Map<String, Object> currMap : directList) {
                        curtimeObj = currMap.get("timestamp");
                        if (curtimeObj != null) {
                            dataTime = (LocalDateTime) curtimeObj;
                            ZoneId zoneId = ZoneId.systemDefault();
                            ZonedDateTime zdt = dataTime.atZone(zoneId);
                            dateTemp = Date.from(zdt.toInstant());

                            timeCurrent = dateTemp.getTime();
                            timeDiff = Math.abs(timeCurrent - timeTarget);
                            if (timeDiff == 0) {
                                timeDiffEnd = 0L;
                                endObj = currMap;
                                break;
                            } else {
                                if (timeDiffEnd == null) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                } else if (timeDiff < timeDiffEnd) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                }
                            }
                        }
                    }
                }
                if (endObj != null && timeDiffEnd < intervalParam * 60000 * 0.9) {

                    if (vo1 != null) {
                        vo1.setDirection(StringUtils.trimNull(endObj.get("tagvalue")));
                        vo1.setDirectionId(StringUtils.trimNull(endObj.get("tagid")));
                    }
                }
            }
            // 查询方向end
            // 查询振动量start
            List<Map<String, Object>> viarantvalueList = typeDataList.get(CollectConsts.VIARANTVALUE_PV);
            for (Date date : dateList) {
                timeTarget = date.getTime();
                timeDiffEnd = null;
                endObj = null;
                if (viarantvalueList != null) {
                    for (Map<String, Object> currMap : viarantvalueList) {
                        curtimeObj = currMap.get("timestamp");
                        if (curtimeObj != null) {
                            dataTime = (LocalDateTime) curtimeObj;
                            ZoneId zoneId = ZoneId.systemDefault();
                            ZonedDateTime zdt = dataTime.atZone(zoneId);
                            dateTemp = Date.from(zdt.toInstant());

                            timeCurrent = dateTemp.getTime();
                            timeDiff = Math.abs(timeCurrent - timeTarget);
                            if (timeDiff == 0) {
                                timeDiffEnd = 0L;
                                endObj = currMap;
                                break;
                            } else {
                                if (timeDiffEnd == null) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                } else if (timeDiff < timeDiffEnd) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                }
                            }
                        }
                    }
                }
                if (endObj != null && timeDiffEnd < intervalParam * 60000 * 0.9) {
                    VibarateVo vo1 = keyVibarateVo.get(timeTarget);
                    if (vo1 != null) {
                        vo1.setVibrateValue(StringUtils.trimNull(endObj.get("tagvalue")));
                        vo1.setVibrateValueId(StringUtils.trimNull(endObj.get("tagid")));
                    }
                }
            }
            // 查询振动量end
            // 查询振动持续时间start
            List<Map<String, Object>> durationList = typeDataList.get(CollectConsts.VIARANTDURATION_PV);
            for (Date date : dateList) {
                timeTarget = date.getTime();
                timeDiffEnd = null;
                endObj = null;
                if (durationList != null) {
                    for (Map<String, Object> currMap : durationList) {
                        curtimeObj = currMap.get("timestamp");
                        if (curtimeObj != null) {
                            dataTime = (LocalDateTime) curtimeObj;
                            ZoneId zoneId = ZoneId.systemDefault();
                            ZonedDateTime zdt = dataTime.atZone(zoneId);
                            dateTemp = Date.from(zdt.toInstant());

                            timeCurrent = dateTemp.getTime();
                            timeDiff = Math.abs(timeCurrent - timeTarget);
                            if (timeDiff == 0) {
                                timeDiffEnd = 0L;
                                endObj = currMap;
                                break;
                            } else {
                                if (timeDiffEnd == null) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                } else if (timeDiff < timeDiffEnd) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                }
                            }
                        }
                    }
                }
                if (endObj != null && timeDiffEnd < intervalParam * 60000 * 0.9) {
                    VibarateVo vo1 = keyVibarateVo.get(timeTarget);
                    if (vo1 != null) {
                        vo1.setDuration(StringUtils.trimNull(endObj.get("tagvalue")));
                        vo1.setDurationId(StringUtils.trimNull(endObj.get("tagid")));
                    }
                }
            }
            // 查询振动持续时间end
            // 查询振动状态start
            List<Map<String, Object>> variantstatusList = typeDataList.get(CollectConsts.VARIANTSTATUS_PV);
            for (Date date : dateList) {
                timeTarget = date.getTime();
                timeDiffEnd = null;
                endObj = null;
                if (variantstatusList != null) {
                    for (Map<String, Object> currMap : variantstatusList) {
                        curtimeObj = currMap.get("timestamp");
                        if (curtimeObj != null) {
                            dataTime = (LocalDateTime) curtimeObj;
                            ZoneId zoneId = ZoneId.systemDefault();
                            ZonedDateTime zdt = dataTime.atZone(zoneId);
                            dateTemp = Date.from(zdt.toInstant());

                            timeCurrent = dateTemp.getTime();
                            timeDiff = Math.abs(timeCurrent - timeTarget);
                            if (timeDiff == 0) {
                                timeDiffEnd = 0L;
                                endObj = currMap;
                                break;
                            } else {
                                if (timeDiffEnd == null) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                } else if (timeDiff < timeDiffEnd) {
                                    timeDiffEnd = timeDiff;
                                    endObj = currMap;
                                }
                            }
                        }
                    }
                }
                if (endObj != null && timeDiffEnd < intervalParam * 60000 * 0.9) {
                    VibarateVo vo1 = keyVibarateVo.get(timeTarget);
                    if (vo1 != null) {
                        vo1.setVibarateStatus(StringUtils.trimNull(endObj.get("tagvalue")));
                        vo1.setVibarateStatusId(StringUtils.trimNull(endObj.get("tagid")));
                    }
                }
            }
            // 查询振动状态start
        }

        List<Map<String, Object>> retDataList = new ArrayList<Map<String, Object>>();
        Map<String, Object> oneMap = null;
        for (Date dateParam : dateList) {
            oneMap = new HashMap<String, Object>();
            oneMap.put("occurTime", DateUtils.formatTime(dateParam));
            retDataList.add(oneMap);
        }

        PageResult pageResult = new PageResult();
        if ("1".equals(runningRecordType)) {
            retVoTemperatureList.stream().forEach(item -> item.setId(IdUtils.uuid32()));
            pageResult.setData(retVoTemperatureList);
        } else if ("2".equals(runningRecordType)) {
            retVoVibarateList.stream().forEach(item -> item.setId(IdUtils.uuid32()));
            pageResult.setData(retVoVibarateList);
        }

        pageResult.setTotalCount(new Long(interval.getTotal()));
        pageResult.setPageNo((long) interval.getPageNo());
        pageResult.setPageSize((long) interval.getPageSize());
        pageResult.setTotalPage((int) interval.getPageTotal().intValue());
        return BusiResponse.OK(pageResult);

    }

    public int getYear(Date currentTime) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(currentTime);
        int currentYear = cal.get(Calendar.YEAR);
        return currentYear;
    }

    @PostMapping(value = "/list")
    @ApiOperation(value = "采集数据表功能:分页查询列表")
    public BusiResponse list(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<CollectData> queryWrapper = RequestConver.getPostParam(pageInfo);
        queryWrapper.ne("del_flag", "1");
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<CollectData> page = new Page<>((Integer) pageInfo.get("pageNo"), (Integer) pageInfo.get("pageSize"));
            Page<CollectData> page1 = collectDataService.page(page, queryWrapper);
            page1.getRecords().forEach(item -> {
            });
            /* 计算分页信息返回给前端 */
            PageResult pageResult = SystemUtil.parsePage(page, page1);
            return BusiResponse.OK(pageResult);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/listAll")
    @ApiOperation(value = "采集数据表功能:查询列表(不带分页)")
    public BusiResponse listAll(HttpServletRequest request) {
        QueryWrapper<CollectData> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.ne("del_flag", "1");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        List<CollectData> list = collectDataService.list(queryWrapper);
        list.forEach(item -> {
        });
        if (list != null && list.size() > 0) {
            return BusiResponse.OK(list);
        } else {
            return BusiResponse.ok("没有查询到数据！");
        }
    }

    @PostMapping(value = "/addTemperature")
    @ApiOperation(value = "采集数据表功能:新增")
    public BusiResponse addTemperature(@RequestBody TemperatureVo vo) {
        String runningRecordType = "1";
        String equipId = vo.getEquipId();
        String remarks = vo.getRemarks();
        // 查询设备信息
        HfResEquip equip = hfResEquipService.getById(equipId);
        String equipCode = "";
        if (equip == null) {
            return BusiResponse.error(400, "设备未查询到！");
        } else {
            runningRecordType = equip.getEquipTypeCode();
            equipCode = equip.getEquipCode();
        }

        if ("".equals(equip.getEquipCode())) {
            return BusiResponse.error(400, "设备编号未查询到！");
        }
        Date runningTime = vo.getRunningTime();
        int year = getYear(runningTime);
        String tableName = CollectConsts.TABLE_PREFIX + equipCode + "_" + year;
        String tagName = "";
        String tagValue = "";
        String runTimeString = DateUtils.formatTime(runningTime, DateUtils.YYYY_MM_DD_HH_MM_SS);
        String sql = "";
        try {
            int count = collectdbDataSourceService.selectCount("select count(1) from " + tableName + " ");
        } catch (Exception e) {
            e.printStackTrace();
            return BusiResponse.error(400,
                    "设备[" + equip.getEquipName() + "]在采集数据库缺少表[" + equipCode + "_" + year + "]请检查采集数据库表的配置！");
        }

        // 温度实测值
        tagName = CollectConsts.TEMPERATURE_PV;
        tagValue = vo.getTemperature();
        if (tagValue != null && !"".equals(tagValue)) {
            sql = "INSERT INTO " + tableName
                    + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                    + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                    + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
            collectdbDataSourceService.insert(sql);
        }
        // 湿度实测值
        tagName = CollectConsts.HUMIDITY_PV;
        tagValue = vo.getHumidity();
        if (tagValue != null && !"".equals(tagValue)) {
            sql = "INSERT INTO " + tableName
                    + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                    + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                    + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
            collectdbDataSourceService.insert(sql);
        }
        // 气压实测值
        tagName = CollectConsts.PRESSURE_PV;
        tagValue = vo.getAirPressure();
        if (tagValue != null && !"".equals(tagValue)) {
            sql = "INSERT INTO " + tableName
                    + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                    + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                    + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
            collectdbDataSourceService.insert(sql);
        }
        // 试验性质数据值
        tagName = CollectConsts.TESTPROPERY_PV;
        tagValue = vo.getTestProperty();
        if (tagValue != null && !"".equals(tagValue)) {
            sql = "INSERT INTO " + tableName
                    + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                    + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                    + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
            collectdbDataSourceService.insert(sql);
        }

        return BusiResponse.ok("添加成功");
    }

    @PostMapping(value = "/addVibarate")
    @ApiOperation(value = "采集数据表功能:新增")
    public BusiResponse addVibarate(@RequestBody VibarateVo vo) {
        String runningRecordType = "2";
        String equipId = vo.getEquipId();
        String remarks = vo.getRemarks();
        // 查询设备信息
        HfResEquip equip = hfResEquipService.getById(equipId);
        String equipCode = "";
        if (equip == null) {
            return BusiResponse.error(400, "设备未查询到！");
        } else {
            runningRecordType = equip.getEquipTypeCode();
            equipCode = equip.getEquipCode();
        }

        if ("".equals(equip.getEquipCode())) {
            return BusiResponse.error(400, "设备编号未查询到！");
        }
        Date runningTime = vo.getRunningTime();
        int year = getYear(runningTime);
        String tableName = CollectConsts.TABLE_PREFIX + equipCode + "_" + year;
        String tagName = "";
        String tagValue = "";
        String runTimeString = DateUtils.formatTime(runningTime, DateUtils.YYYY_MM_DD_HH_MM_SS);
        String sql = "";
        try {
            int count = collectdbDataSourceService.selectCount("select count(1) from " + tableName + " ");
        } catch (Exception e) {
            e.printStackTrace();
            return BusiResponse.error(400,
                    "设备[" + equip.getEquipName() + "]在采集数据库缺少表[" + equipCode + "_" + year + "]请检查采集数据库表的配置！");
        }

        // 振动方向实测值
        tagName = CollectConsts.VIARANTDIRECT_PV;
        tagValue = vo.getDirection();
        if (tagValue != null && !"".equals(tagValue)) {
            sql = "INSERT INTO " + tableName
                    + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                    + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                    + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
            collectdbDataSourceService.insert(sql);
        }
        // 振动量（g）实测值
        tagName = CollectConsts.VIARANTVALUE_PV;
        tagValue = vo.getVibrateValue();
        if (tagValue != null && !"".equals(tagValue)) {
            sql = "INSERT INTO " + tableName
                    + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                    + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                    + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
            collectdbDataSourceService.insert(sql);
        }
        // 振动持续时间（min）实测值
        tagName = CollectConsts.VIARANTDURATION_PV;
        tagValue = vo.getDuration();
        if (tagValue != null && !"".equals(tagValue)) {
            sql = "INSERT INTO " + tableName
                    + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                    + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                    + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
            collectdbDataSourceService.insert(sql);
        }
        // 振动状态实测值
        tagName = CollectConsts.VARIANTSTATUS_PV;
        tagValue = vo.getVibarateStatus();
        if (tagValue != null && !"".equals(tagValue)) {
            sql = "INSERT INTO " + tableName
                    + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                    + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                    + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
            collectdbDataSourceService.insert(sql);
        }

        return BusiResponse.ok("添加成功");
    }

    @PostMapping(value = "/editTemperature")
    @ApiOperation(value = "采集数据表功能:新增")
    public BusiResponse editTemperature(@RequestBody TemperatureVo vo) {
        String runningRecordType = "1";
        String equipId = vo.getEquipId();
        String remarks = vo.getRemarks();
        // 查询设备信息
        HfResEquip equip = hfResEquipService.getById(equipId);
        String equipCode = "";
        if (equip == null) {
            return BusiResponse.error(400, "设备未查询到！");
        } else {
            runningRecordType = equip.getEquipTypeCode();
            equipCode = equip.getEquipCode();
        }

        if ("".equals(equip.getEquipCode())) {
            return BusiResponse.error(400, "设备编号未查询到！");
        }
        Date runningTime = vo.getRunningTime();
        int year = getYear(runningTime);
        String tableName = CollectConsts.TABLE_PREFIX + equipCode + "_" + year;
        String tagName = "";
        String tagValue = "";
        String runTimeString = DateUtils.formatTime(runningTime, DateUtils.YYYY_MM_DD_HH_MM_SS);
        String sql = "";
        try {
            int count = collectdbDataSourceService.selectCount("select count(1) from " + tableName + " ");
        } catch (Exception e) {
            e.printStackTrace();
            return BusiResponse.error(400,
                    "设备[" + equip.getEquipName() + "]在采集数据库缺少表[" + equipCode + "_" + year + "]请检查采集数据库表的配置！");
        }
        String tagId = "";

        // 温度实测值
        tagName = CollectConsts.TEMPERATURE_PV;
        tagValue = vo.getTemperature();
        tagId = vo.getTemperatureId();
        if (tagValue != null && !"".equals(tagValue)) {
            if (tagId == null || tagId.equals("")) {
                sql = "INSERT INTO " + tableName
                        + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                        + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                        + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
                collectdbDataSourceService.insert(sql);
            } else {
                sql = "update " + tableName + " set TAGVALUE='" + tagValue + "',USERNAME='" + SystemLoginUser.idName
                        + "',REMARKS='" + remarks + "' where TAGID='" + tagId + "'  ";
                collectdbDataSourceService.update(sql);
            }

        }
        // 湿度实测值
        tagName = CollectConsts.HUMIDITY_PV;
        tagValue = vo.getHumidity();
        tagId = vo.getHumidityId();
        if (tagValue != null && !"".equals(tagValue)) {
            if (tagId == null || tagId.equals("")) {
                sql = "INSERT INTO " + tableName
                        + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                        + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                        + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
                collectdbDataSourceService.insert(sql);
            } else {
                sql = "update " + tableName + " set TAGVALUE='" + tagValue + "',USERNAME='" + SystemLoginUser.idName
                        + "',REMARKS='" + remarks + "' where TAGID='" + tagId + "'  ";
                collectdbDataSourceService.update(sql);
            }

        }
        // 气压实测值
        tagName = CollectConsts.PRESSURE_PV;
        tagValue = vo.getAirPressure();
        tagId = vo.getAirPressureId();
        if (tagValue != null && !"".equals(tagValue)) {
            if (tagId == null || tagId.equals("")) {
                sql = "INSERT INTO " + tableName
                        + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                        + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                        + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
                collectdbDataSourceService.insert(sql);
            } else {
                sql = "update " + tableName + " set TAGVALUE='" + tagValue + "',USERNAME='" + SystemLoginUser.idName
                        + "',REMARKS='" + remarks + "' where TAGID='" + tagId + "'  ";
                collectdbDataSourceService.update(sql);
            }
        }
        // 试验性质数据值
        tagName = CollectConsts.TESTPROPERY_PV;
        tagValue = vo.getTestProperty();
        tagId = vo.getTestPropertyId();
        if (tagValue != null && !"".equals(tagValue)) {
            if (tagId == null || tagId.equals("")) {
                sql = "INSERT INTO " + tableName
                        + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                        + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                        + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
                collectdbDataSourceService.insert(sql);
            } else {
                sql = "update " + tableName + " set TAGVALUE='" + tagValue + "',USERNAME='" + SystemLoginUser.idName
                        + "',REMARKS='" + remarks + "' where TAGID='" + tagId + "'  ";
                collectdbDataSourceService.update(sql);
            }

        }

        return BusiResponse.ok("修改成功");
    }

    @PostMapping(value = "/editVibarate")
    @ApiOperation(value = "采集数据表功能:新增")
    public BusiResponse editVibarate(@RequestBody VibarateVo vo) {
        String runningRecordType = "2";
        String equipId = vo.getEquipId();
        String remarks = vo.getRemarks();
        // 查询设备信息
        HfResEquip equip = hfResEquipService.getById(equipId);
        String equipCode = "";
        if (equip == null) {
            return BusiResponse.error(400, "设备未查询到！");
        } else {
            runningRecordType = equip.getEquipTypeCode();
            equipCode = equip.getEquipCode();
        }

        if ("".equals(equip.getEquipCode())) {
            return BusiResponse.error(400, "设备编号未查询到！");
        }
        Date runningTime = vo.getRunningTime();
        int year = getYear(runningTime);
        String tableName = CollectConsts.TABLE_PREFIX + equipCode + "_" + year;
        String tagName = "";
        String tagValue = "";
        String runTimeString = DateUtils.formatTime(runningTime, DateUtils.YYYY_MM_DD_HH_MM_SS);
        String sql = "";
        try {
            int count = collectdbDataSourceService.selectCount("select count(1) from " + tableName + " ");
        } catch (Exception e) {
            e.printStackTrace();
            return BusiResponse.error(400,
                    "设备[" + equip.getEquipName() + "]在采集数据库缺少表[" + equipCode + "_" + year + "]请检查采集数据库表的配置！");
        }

        String tagId = "";

        // 振动方向实测值
        tagName = CollectConsts.VIARANTDIRECT_PV;
        tagValue = vo.getDirection();
        tagId = vo.getDirectionId();
        if (tagValue != null && !"".equals(tagValue)) {
            if (tagId == null || tagId.equals("")) {
                sql = "INSERT INTO " + tableName
                        + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                        + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                        + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
                collectdbDataSourceService.insert(sql);
            } else {
                sql = "update " + tableName + " set TAGVALUE='" + tagValue + "',USERNAME='" + SystemLoginUser.idName
                        + "',REMARKS='" + remarks + "' where TAGID='" + tagId + "'  ";
                collectdbDataSourceService.update(sql);
            }
        }
        // 振动量（g）实测值
        tagName = CollectConsts.VIARANTVALUE_PV;
        tagValue = vo.getVibrateValue();
        tagId = vo.getVibrateValueId();
        if (tagValue != null && !"".equals(tagValue)) {
            if (tagId == null || tagId.equals("")) {
                sql = "INSERT INTO " + tableName
                        + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                        + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                        + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
                collectdbDataSourceService.insert(sql);
            } else {
                sql = "update " + tableName + " set TAGVALUE='" + tagValue + "',USERNAME='" + SystemLoginUser.idName
                        + "',REMARKS='" + remarks + "' where TAGID='" + tagId + "'  ";
                collectdbDataSourceService.update(sql);
            }
        }
        // 振动持续时间（min）实测值
        tagName = CollectConsts.VIARANTDURATION_PV;
        tagValue = vo.getDuration();
        tagId = vo.getDurationId();
        if (tagValue != null && !"".equals(tagValue)) {
            if (tagId == null || tagId.equals("")) {
                sql = "INSERT INTO " + tableName
                        + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                        + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                        + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
                collectdbDataSourceService.insert(sql);
            } else {
                sql = "update " + tableName + " set TAGVALUE='" + tagValue + "',USERNAME='" + SystemLoginUser.idName
                        + "',REMARKS='" + remarks + "' where TAGID='" + tagId + "'  ";
                collectdbDataSourceService.update(sql);
            }
        }
        // 振动状态实测值
        tagName = CollectConsts.VARIANTSTATUS_PV;
        tagValue = vo.getVibarateStatus();
        tagId = vo.getVibarateStatusId();
        if (tagValue != null && !"".equals(tagValue)) {
            if (tagId == null || tagId.equals("")) {
                sql = "INSERT INTO " + tableName
                        + " (TAGID,TAGNAME,TAGVALUE,TIMESTAMP,TAGTYPE,ALARMUPPERLIMIT,ALARMLOWERLIMIT,ALARMSTATUS,ALARMINFO,USERNAME,REMARKS) "
                        + "VALUES ('" + IdUtils.uuid32() + "','" + tagName + "','" + tagValue + "','" + runTimeString
                        + "',1,NULL,NULL,3,NULL,'" + SystemLoginUser.idName + "','" + remarks + "');" + "";
                collectdbDataSourceService.insert(sql);
            } else {
                sql = "update " + tableName + " set TAGVALUE='" + tagValue + "',USERNAME='" + SystemLoginUser.idName
                        + "',REMARKS='" + remarks + "' where TAGID='" + tagId + "'  ";
                collectdbDataSourceService.update(sql);
            }
        }

        return BusiResponse.ok("修改成功");
    }

    @PostMapping(value = "/deleteTemperature")
    @ApiOperation(value = "采集数据表功能:新增")
    public BusiResponse deleteTemperature(@RequestBody TemperatureVo vo) {
        String runningRecordType = "1";
        String equipId = vo.getEquipId();
        String remarks = vo.getRemarks();
        // 查询设备信息
        HfResEquip equip = hfResEquipService.getById(equipId);
        String equipCode = "";
        if (equip == null) {
            return BusiResponse.error(400, "设备未查询到！");
        } else {
            runningRecordType = equip.getEquipTypeCode();
            equipCode = equip.getEquipCode();
        }

        if ("".equals(equip.getEquipCode())) {
            return BusiResponse.error(400, "设备编号未查询到！");
        }
        Date runningTime = vo.getRunningTime();
        int year = getYear(runningTime);
        String tableName = CollectConsts.TABLE_PREFIX + equipCode + "_" + year;
        String tagName = "";
        String tagValue = "";
        String runTimeString = DateUtils.formatTime(runningTime, DateUtils.YYYY_MM_DD_HH_MM_SS);
        String sql = "";
        try {
            int count = collectdbDataSourceService.selectCount("select count(1) from " + tableName + " ");
        } catch (Exception e) {
            e.printStackTrace();
            return BusiResponse.error(400,
                    "设备[" + equip.getEquipName() + "]在采集数据库缺少表[" + equipCode + "_" + year + "]请检查采集数据库表的配置！");
        }
        String tagId = "";

        // 温度实测值
        tagName = CollectConsts.TEMPERATURE_PV;
        tagValue = vo.getTemperature();
        tagId = vo.getTemperatureId();

        if (tagId == null || tagId.equals("")) {

        } else {
            sql = "delete from " + tableName + "   where TAGID='" + tagId + "'  ";
            collectdbDataSourceService.update(sql);
        }

        // 湿度实测值
        tagName = CollectConsts.HUMIDITY_PV;
        tagValue = vo.getHumidity();
        tagId = vo.getHumidityId();

        if (tagId == null || tagId.equals("")) {

        } else {
            sql = "delete from " + tableName + "   where TAGID='" + tagId + "'  ";
            collectdbDataSourceService.update(sql);
        }

        // 气压实测值
        tagName = CollectConsts.PRESSURE_PV;
        tagValue = vo.getAirPressure();
        tagId = vo.getAirPressureId();

        if (tagId == null || tagId.equals("")) {

        } else {
            sql = "delete from " + tableName + "   where TAGID='" + tagId + "'  ";
            collectdbDataSourceService.update(sql);
        }

        // 试验性质数据值
        tagName = CollectConsts.TESTPROPERY_PV;
        tagValue = vo.getTestProperty();
        tagId = vo.getAirPressureId();

        if (tagId == null || tagId.equals("")) {

        } else {
            sql = "delete from " + tableName + "   where TAGID='" + tagId + "'  ";
            collectdbDataSourceService.update(sql);
        }

        return BusiResponse.ok("删除成功");
    }

    @PostMapping(value = "/deleteVibarate")
    @ApiOperation(value = "采集数据表功能:新增")
    public BusiResponse deleteVibarate(@RequestBody VibarateVo vo) {
        String runningRecordType = "2";
        String equipId = vo.getEquipId();
        String remarks = vo.getRemarks();
        // 查询设备信息
        HfResEquip equip = hfResEquipService.getById(equipId);
        String equipCode = "";
        if (equip == null) {
            return BusiResponse.error(400, "设备未查询到！");
        } else {
            runningRecordType = equip.getEquipTypeCode();
            equipCode = equip.getEquipCode();
        }

        if ("".equals(equip.getEquipCode())) {
            return BusiResponse.error(400, "设备编号未查询到！");
        }
        Date runningTime = vo.getRunningTime();
        int year = getYear(runningTime);
        String tableName = CollectConsts.TABLE_PREFIX + equipCode + "_" + year;
        String tagName = "";
        String tagValue = "";
        String runTimeString = DateUtils.formatTime(runningTime, DateUtils.YYYY_MM_DD_HH_MM_SS);
        String sql = "";
        try {
            int count = collectdbDataSourceService.selectCount("select count(1) from " + tableName + " ");
        } catch (Exception e) {
            e.printStackTrace();
            return BusiResponse.error(400,
                    "设备[" + equip.getEquipName() + "]在采集数据库缺少表[" + equipCode + "_" + year + "]请检查采集数据库表的配置！");
        }

        String tagId = "";

        // 振动方向实测值
        tagName = CollectConsts.VIARANTDIRECT_PV;
        tagValue = vo.getDirection();
        tagId = vo.getDirectionId();

        if (tagId == null || tagId.equals("")) {

        } else {
            sql = "delete from " + tableName + "   where TAGID='" + tagId + "'  ";
            collectdbDataSourceService.update(sql);
        }

        // 振动量（g）实测值
        tagName = CollectConsts.VIARANTVALUE_PV;
        tagValue = vo.getVibrateValue();
        tagId = vo.getVibrateValueId();

        if (tagId == null || tagId.equals("")) {

        } else {
            sql = "delete from " + tableName + "   where TAGID='" + tagId + "'  ";
            collectdbDataSourceService.update(sql);
        }

        // 振动持续时间（min）实测值
        tagName = CollectConsts.VIARANTDURATION_PV;
        tagValue = vo.getDuration();
        tagId = vo.getDurationId();

        if (tagId == null || tagId.equals("")) {

        } else {
            sql = "delete from " + tableName + "   where TAGID='" + tagId + "'  ";
            collectdbDataSourceService.update(sql);
        }

        // 振动状态实测值
        tagName = CollectConsts.VARIANTSTATUS_PV;
        tagValue = vo.getVibarateStatus();
        tagId = vo.getVibarateStatusId();

        if (tagId == null || tagId.equals("")) {

        } else {
            sql = "delete from " + tableName + "   where TAGID='" + tagId + "'  ";
            collectdbDataSourceService.update(sql);
        }

        return BusiResponse.ok("删除成功");
    }

    @PostMapping(value = "/addTemperature2")
    @ApiOperation(value = "采集数据表功能:新增")
    public BusiResponse addTemperature2(@RequestBody CollectData collectData) {

        collectDataService.save(collectData);
        return BusiResponse.ok("添加成功");
    }

    @PostMapping(value = "/edit")
    @ApiOperation(value = "采集数据表功能:编辑")
    public BusiResponse edit(@RequestBody CollectData collectData) {
        collectDataService.updateById(collectData);
        return BusiResponse.ok("编辑成功！");
    }

    @GetMapping("/queryById")
    @ApiOperation(value = "采集数据表功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam(name = "id") String id) {
        CollectData byId = collectDataService.getById(id);
        // 查询转换附件
        return BusiResponse.OK(byId);
    }

    @ApiOperation("新增气候设备运行记录")
    @PostMapping("/batchAddClimate")
    public BusiResponse batchAddClimate(@RequestBody @Validated ClimateCollectDataBatchAddVO collectDataAddVO) {
        collectDataService.batchAddClimateData(collectDataAddVO);
        return BusiResponse.OK();
    }

    @ApiOperation("新增力学设备运行记录")
    @PostMapping("/batchAddDynamics")
    public BusiResponse batchAddDynamics(@RequestBody @Validated DynamicsCollectDataBatchAddVO collectDataAddVO) {
        collectDataService.batchAddDynamicsData(collectDataAddVO);
        return BusiResponse.OK();
    }

    @ApiOperation("新增气候设备运行记录")
    @PostMapping("/addClimate")
    public BusiResponse addClimate(@RequestBody @Validated ClimateCollectDataAddVO collectDataAddVO) {
        collectDataService.addClimateData(collectDataAddVO);
        return BusiResponse.OK();
    }

    @ApiOperation("新增力学设备运行记录")
    @PostMapping("/addDynamics")
    public BusiResponse addDynamics(@RequestBody @Validated DynamicsCollectDataAddVO dynamicsCollectDataAddVO) {
        collectDataService.addDynamicsData(dynamicsCollectDataAddVO);
        return BusiResponse.OK();
    }


    @ApiOperation("编辑力学设备运行记录")
    @PostMapping("/editDynamics")
    public BusiResponse editDynamics(@RequestBody @Validated DynamicsCollectDataVO dynamicsCollectDataVO) {
        collectDataService.editDynamics(dynamicsCollectDataVO);
        return BusiResponse.OK();
    }

    @ApiOperation("编辑气候设备运行记录")
    @PostMapping("/editClimate")
    public BusiResponse editClimate(@RequestBody @Validated ClimateCollectDataVO climateCollectDataVO) {
        collectDataService.editClimate(climateCollectDataVO);
        return BusiResponse.OK();
    }

    @ApiOperation("删除设备运行记录")
    @PostMapping("/delete")
    public BusiResponse delete(@RequestBody @Validated CollectDataDeleteVO collectDataDeleteVO) {
        collectDataService.delete(collectDataDeleteVO);
        return BusiResponse.OK();
    }

}